package com.plian.system.service.pf.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.pf.BasePerformanceEffect;
import com.plian.system.entity.pf.PerformanceScoreMethod;
import com.plian.system.enumeratea.BusinessIndicatorsStatus;
import com.plian.system.mapper.pf.BasePerformanceEffectMapper;
import com.plian.system.model.ObjResult;
import com.plian.system.mybatis.base.BaseFlowService;
import com.plian.system.mybatis.base.BaseServiceImpl;
import com.plian.system.service.pf.IPerformanceScoreChangeService;
import com.plian.system.service.pf.IPerformanceScoreMethodService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.pf.BasePerformanceEffectVO;
import com.plian.system.wrapper.pf.BasePerformanceEffectWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.plian.system.constant.sys.FormStatusConstant.UNREVIEWED;

/**
 * @Author: Take-off
 * @Description: TODO 履职成效考评内容-变更-服务类
 * @Date: 2023/1/30 5:03 PM
 * @Version: 1.0
 **/
@Slf4j
@Service
@AllArgsConstructor
public class PerformanceScoreChangeServiceImpl extends BaseServiceImpl<BasePerformanceEffectMapper, BasePerformanceEffect> implements IPerformanceScoreChangeService, BaseFlowService {

    private IPerformanceScoreMethodService performanceScoreMethodService;

    private BasePerformanceEffectWrapper basePerformanceEffectWrapper;

    private FormWorkflowService formWorkflowService;

    @Override
    public boolean saveOrUpdate(BasePerformanceEffect basePerformanceEffect) {
        if (!Optional.ofNullable(basePerformanceEffect.getStatus()).isPresent()) {
            basePerformanceEffect.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (basePerformanceEffect.getStatus().equals(FormStatusConstant.REJECT)) {
            basePerformanceEffect.setStatus(FormStatusConstant.UNREVIEWED);
        }
        if (!Optional.ofNullable(basePerformanceEffect.getId()).isPresent()) {
            basePerformanceEffect.setFormType(String.valueOf(FormTypeConstant.PF_PERFORMANCE_SCORE_CHANGE));
            basePerformanceEffect.setVersion(basePerformanceEffect.getVersion() + 1);
            basePerformanceEffect.setIsLatest(1);
            basePerformanceEffect.setIndicatorStatus(BusinessIndicatorsStatus.CHANGE_AUDIT.getStatus());
            updateLangStatus(basePerformanceEffect.getInitialId(), BusinessIndicatorsStatus.CHANGE_AUDIT.getStatus());

        }
        return super.saveOrUpdate(basePerformanceEffect);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean deleteLogic(List<Long> ids) {
        for (Long id : ids) {
            BasePerformanceEffect basePerformanceEffect = getById(id);
            if (basePerformanceEffect == null) {
                return false;
            }
            updateLangStatus(basePerformanceEffect.getInitialId(), BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
            update(Wrappers.<BasePerformanceEffect>lambdaUpdate()
                    .eq(BasePerformanceEffect::getInitialId, basePerformanceEffect.getInitialId())
                    .eq(BasePerformanceEffect::getVersion, basePerformanceEffect.getVersion() - 1)
                    .set(BasePerformanceEffect::getIsLatest, 2));
            formWorkflowService.deleteProcessInstance(String.valueOf(id));

        }
        boolean result = super.deleteLogic(ids);
        if (result){
            performanceScoreMethodService.deleteByParentId(ids);
        }
        return result;
    }

    @Override
    public HashMap<String,Object> commit(String id) {
        handleStatus(Long.valueOf(id), FormStatusConstant.FLOW);
        //将需要提交的流程变量返回，用于工作流侧
        return new HashMap<String,Object>();
    }

    @Override
    public Boolean finish(String id) {
        BasePerformanceEffect performanceEffect = getById(id);
        updateLangStatus(performanceEffect.getInitialId(), BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
        updateIsLatest(performanceEffect.getInitialId());
        performanceEffect.setApprovedUser(TokenUtil.getTokenUserId());
        Date now = DateUtil.now();
        performanceEffect.setApprovedTime(now);
        performanceEffect.setIsLatest(2);
        performanceEffect.setIndicatorStatus(BusinessIndicatorsStatus.ADJUSTABLE.getStatus());
        updateById(performanceEffect);

        return handleStatus(Long.valueOf(id), FormStatusConstant.FINISH);
    }

    @Override
    public Boolean reject(String id, int formState,String comment) {
        return handleStatus(Long.valueOf(id), formState);
    }

    @Override
    public List<PageData> findByIds(List<String> formIds) {
        LambdaQueryWrapper<BasePerformanceEffect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(BasePerformanceEffect::getId, Func.toLongList(StringUtils.join(formIds, StringPool.COMMA)));
        List<BasePerformanceEffect> basePerformanceEffects = list(queryWrapper);
        List<BasePerformanceEffectVO> basePerformanceEffectVOS = basePerformanceEffectWrapper.entityToVO(basePerformanceEffects);
        List<PageData> pageDataList = new ArrayList<>();
        try{
            if (CollectionUtil.isNotEmpty(basePerformanceEffectVOS)){
                for (BasePerformanceEffectVO vo : basePerformanceEffectVOS){
                    PageData pd = new PageData();
                    pd.put("id", vo.getId());
                    pd.put("UNITNAME", vo.getReportOfficeName());
                    pd.put("APPLICANTNAME", vo.getCreateUserName());
                    pd.put("applicantId", vo.getCreateUser());
                    pd.put("applyOrganizationId", vo.getReportOffice());
                    pd.put("formType", FormTypeConstant.PF_PERFORMANCE_SCORE_CHANGE);
                    pd.put("orgName", vo.getReportOfficeName());
                    pageDataList.add(pd);
                }
            }

            return pageDataList;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return pageDataList;
    }

    @Override
    public List<Integer> getFormType() {
        return Arrays.asList(FormTypeConstant.PF_PERFORMANCE_SCORE_CHANGE);
    }

    @Override
    public void goBackToStash(String formId) {
        Long id = Long.valueOf(formId);
        BasePerformanceEffect performanceEffect = getById(id);
        if (performanceEffect.getStatus() == FormStatusConstant.FINISH){
            if (performanceEffect.getIsLatest() != null && performanceEffect.getIsLatest() != 2){
                throw new MyRuntimeException(new ObjResult("该信息不是最新  不可回退！"));
            }
            LambdaUpdateWrapper<BasePerformanceEffect> updateWrapper = new LambdaUpdateWrapper<>();
            update(updateWrapper.eq(BasePerformanceEffect::getId, id)
                    .set(BasePerformanceEffect::getApprovedUser, null).set(BasePerformanceEffect::getApprovedTime, null));
            updateLangStatus(performanceEffect.getInitialId(), BusinessIndicatorsStatus.CHANGE_AUDIT.getStatus());
            updateIsLatest(performanceEffect.getInitialId());
            List<BasePerformanceEffect> performanceEffects = list(new LambdaUpdateWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, id)
                    .orderByDesc(BasePerformanceEffect::getVersion));
            if (CollectionUtil.isNotEmpty(performanceEffects) && performanceEffects.size() > 1){
                BasePerformanceEffect basePerformanceEffect = performanceEffects.get(1);
                basePerformanceEffect.setIsLatest(2);
                updateById(basePerformanceEffect);
            }
        }
        handleStatus(Long.valueOf(formId), UNREVIEWED);
    }

    @Override
    @Transactional(rollbackFor=RuntimeException.class)
    public boolean submit(BasePerformanceEffect basePerformanceEffect) {
        boolean result = saveOrUpdate(basePerformanceEffect);
        if (result){
            List<PerformanceScoreMethod> performanceScoreMethods = basePerformanceEffect.getPerformanceScoreMethods();
            if (CollectionUtil.isNotEmpty(performanceScoreMethods)){
                for (PerformanceScoreMethod scoreMethod : performanceScoreMethods){
                    if (scoreMethod.getId() != null &&
                            Optional.ofNullable(scoreMethod.getIsDeleted()).isPresent() && scoreMethod.getIsDeleted().intValue() == 1) {
                        performanceScoreMethodService.removeById(scoreMethod.getId());
                    }else {
                        scoreMethod.setBasePerformanceId(basePerformanceEffect.getId());
                        performanceScoreMethodService.saveOrUpdate(scoreMethod);
                    }
                }
            }
        }
        return result;
    }

    private Boolean handleStatus(Long id, int updateStatus) {
        try {
            BasePerformanceEffect basePerformanceEffect = getById(id);
            /**
             * 设置审批人和审批时间
             */
            if (updateStatus == FormStatusConstant.FINISH){
                basePerformanceEffect.setApprovedUser(TokenUtil.getTokenUserId());
                Date now = DateUtil.now();
                basePerformanceEffect.setApprovedTime(now);
            }
            basePerformanceEffect.setStatus(updateStatus);
            updateById(basePerformanceEffect);
            return true;
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            return false;
        }
    }


    private void updateLangStatus(Long initialId, int landStatus){
        update(new LambdaUpdateWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, initialId).set(BasePerformanceEffect::getIndicatorStatus, landStatus));
    }

    private void updateIsLatest(Long initialId){
        update(new LambdaUpdateWrapper<BasePerformanceEffect>().eq(BasePerformanceEffect::getInitialId, initialId)
                .eq(BasePerformanceEffect::getIsLatest, 2).set(BasePerformanceEffect::getIsLatest, 1));
    }
}
